Managing Data and Processes
Reading Data Interactively
Interactive input allows programs to receive data from users during execution. In Python, the input()
function is used to prompt the user and capture their input.
The input()
Function
-
Syntax:
input(prompt)
-
Returns: A string containing the user's input.
-
Usage:
name = input("Enter your name: ")
Type Conversion
-
Since
input()
returns a string, convert it to other data types as needed:age = int(input("Enter your age: "))
temperature = float(input("Enter the temperature: "))
Example: Time Conversion Program
def to_seconds(hours, minutes, seconds):
return hours * 3600 + minutes * 60 + seconds
print("Welcome to the Time Converter!")
cont = 'y'
while cont.lower() == 'y':
hours = int(input("Enter the number of hours: "))
minutes = int(input("Enter the number of minutes: "))
seconds = int(input("Enter the number of seconds: "))
total_seconds = to_seconds(hours, minutes, seconds)
print(f"That's {total_seconds} seconds.")
cont = input("Do you want to do another conversion? [y/n] ")
- Explanation:
- Function Definition:
to_seconds
converts hours, minutes, and seconds to total seconds. - User Interaction: Prompts the user for input and converts it to integers.
- Loop Control: Continues to prompt the user until they choose not to.
- Function Definition:
Key Points:
- Always validate user input to prevent errors.
- Use
.lower()
or.upper()
to handle case-insensitive comparisons.
Standard Streams
Standard streams are the primary channels for input and output operations in programs. They facilitate interaction between programs and their execution environment.
Types of Standard Streams
- Standard Input (STDIN)
- Purpose: Receives input data (usually from the keyboard).
- In Python: The
input()
function reads from STDIN.
- Standard Output (STDOUT)
- Purpose: Sends output data (usually to the terminal screen).
- In Python: The
print()
function writes to STDOUT.
- Standard Error (STDERR)
- Purpose: Outputs error messages and diagnostics.
- In Python: Error messages and tracebacks are sent to STDERR.
Example: Using Standard Streams
# Reading from STDIN
user_input = input("Enter some data: ")
# Writing to STDOUT
print(f"You entered: {user_input}")
# Generating an error (sent to STDERR)
result = "string" + 5 # This will raise a TypeError
- Explanation:
- The script reads input, echoes it back, and intentionally causes a
TypeError
to demonstrate STDERR.
- The script reads input, echoes it back, and intentionally causes a
Standard Streams in the Shell
-
Commands like
cat
,ls
, andecho
utilize standard streams. -
Error Handling: When a command fails, error messages are sent to STDERR.
-
Example:
$ ls --invalid-option
ls: unrecognized option '--invalid-option'
-
-
Note: STDOUT and STDERR are separate streams, even if they both display output to the terminal.
Environment Variables
Environment variables are key-value pairs that can affect the behavior of running processes on an operating system.
Accessing Environment Variables
-
In the Shell:
-
View all variables with
env
orprintenv
. -
Access a variable using
$VARIABLE_NAME
:$ echo $HOME
/home/username
-
-
In Python:
-
Use the
os
module:import os
home_dir = os.environ.get('HOME', '')
shell = os.environ.get('SHELL', '')
fruit = os.environ.get('FRUIT', '')
print(f"HOME: {home_dir}")
print(f"SHELL: {shell}")
print(f"FRUIT: {fruit}") -
Explanation:
os.environ
is a dictionary containing environment variables..get()
method retrieves the value or returns a default if the key doesn't exist.
-
Important Environment Variables
-
PATH
-
Purpose: Lists directories the shell searches for executable programs.
-
View:
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
-
-
HOME
- Purpose: Indicates the current user's home directory.
-
SHELL
- Purpose: Specifies the path to the user's default shell.
Setting Environment Variables
-
Temporary Export (for current session):
$ export FRUIT="Banana"
-
Permanent Export:
- Add the export command to shell profile files like
~/.bashrc
or~/.bash_profile
.
- Add the export command to shell profile files like
Practical Usage
- Configuration: Store settings like API keys, database credentials, or user preferences.
- Avoid Hardcoding: By using environment variables, scripts become more portable and secure.
Command-Line Arguments and Exit Status
Command-Line Arguments
-
Definition: Values provided to a program at execution time via the command line.
-
Accessing in Python:
import sys
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:]) -
Example Usage:
$ python script.py arg1 arg2 arg3
sys.argv
would be['script.py', 'arg1', 'arg2', 'arg3']
.
-
Handling Arguments:
import sys
if len(sys.argv) < 2:
print("Usage: python script.py <filename>")
sys.exit(1)
filename = sys.argv[1]
print(f"Processing file: {filename}")
Exit Status (Return Codes)
-
Purpose: Indicates the success or failure of a program to the operating system.
-
Conventions:
0
: Success- Non-zero: Failure (specific codes can indicate different errors)
-
Checking Exit Status in Shell:
$ echo $?
- Displays the exit status of the last executed command.
Example: Using Exit Status in Python
import sys
import os
filename = sys.argv[1]
if not os.path.exists(filename):
with open(filename, 'w') as file:
file.write("New file created.\n")
print("File created successfully.")
sys.exit(0)
else:
print("Error: File already exists.")
sys.exit(1)
- Explanation:
- Checks if a file exists.
- Creates the file if it doesn't, exits with status
0
. - If the file exists, prints an error and exits with status
1
.
Testing Exit Status in Shell
$ python script.py myfile.txt
File created successfully.
$ echo $?
0
$ python script.py myfile.txt
Error: File already exists.
$ echo $?
1
Best Practices
- Consistent Exit Codes: Use standard exit codes for common situations.
- Error Messages: Provide clear and informative error messages.
- Automation: Exit statuses allow scripts to be used in larger automation workflows.
Summary
- Interactive Input:
- Use
input()
to receive user data during execution. - Convert input to appropriate data types as needed.
- Use
- Standard Streams:
- STDIN: Input stream (e.g., keyboard input).
- STDOUT: Output stream for standard messages.
- STDERR: Output stream for error messages.
- Environment Variables:
- Access using
os.environ
in Python. - Useful for configuration and avoiding hardcoding.
- Access using
- Command-Line Arguments:
- Accessed via
sys.argv
. - Allow scripts to accept parameters at runtime.
- Accessed via
- Exit Status:
- Indicate success (
0
) or failure (non-zero) of a script. - Check in shell with
echo $?
.
- Indicate success (